const { Server } = require('socket.io');
const DB = require('./db');
// 存储连接的用户
let users = {};
const chat = (app) => {
	const io = new Server(app, { cors: { origin: '*' } });

	io.on('connection', (socket) => {
		console.log('服务器scoket连接成功');

		// 登录
		socket.on('login', (data) => {
			// 存储数据库用户的id 与 socketId 的映射关系
			users[socket.id] = data.userId;

			// 加入房间，这里写死了
			socket.join('zyl');

			let arr = computeUserId(users);
			io.emit('onLineUserList', arr);
		});

		// 接收消息(一对一)
		socket.on('sendSingleMsg', ({ fromId, toId, msg, msgType }) => {
			let toSocktId = '';
			DB.query('insert into t_single_msg (fromId,toId,msg,msgType) values(?,?,?,?)', [fromId, toId, msg, msgType]);
			// 一对一聊天
			for (let key in users) {
				if (users[key] == toId) {
					toSocktId = key;
				}
			}
			io.to(toSocktId).emit('receiveSingleMsg', { fromId, toId, msg, msgType });
		});

		// 接收消息(群消息)
		socket.on('sendGrounpMsg', ({ fromId, grounpId, msg, msgType, avatar, name }) => {
			// 向数据库保存
			DB.query('insert into t_grounp_msg (fromId,msg,grounpId,msgType) values(?,?,?,?)', [fromId, msg, grounpId, msgType]);

			// 群聊
			io.to('zyl').emit('receiveGrounpMsg', { fromId, grounpId, msg, msgType, avatar, name });
		});

		// 断开连接
		socket.on('disconnect', () => {
			console.log('用户断开连接');
			if (users.hasOwnProperty(socket.id)) {
				delete users[socket.id];
				// 离开房间
				socket.leave('zyl');
			}
			let arr = computeUserId(users);
			io.emit('onLineUserList', arr);
		});
	});
};

// 计算在线用户

function computeUserId(users) {
	let userList = [];
	for (let key in users) {
		userList.push(users[key]);
	}
	return [...new Set(userList)];
}

module.exports = chat;
